<template>
  <el-dialog
    v-model="dialogVisible"
    title="导出号码"
    :width="dailogWidth"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      style="max-width: 600px"
      :model="dataForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      v-loading="loading"
    >
      <el-form-item label="导出数量" label-position="right">
        <el-input-number v-model="canNum" controls-position="right" />
        <span style="margin-left: 10px;">可导出：{{ canNumCopy }}</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm" :disabled="loading">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { downloadZipFile } from '@/utils/index'
import { formatParams } from "@/utils";
import { exportAccount, getAccountList } from "@/api/equipmentManagement/account.api.js";
import useToggle from "@/hooks/useToggle";
import useDailogWidth from "@/hooks/useDailogWidth";
const dailogWidth = useDailogWidth("90%", "35%")
const [loading, , setLoading] = useToggle();
const [dialogVisible, , setDialogVisible] = useToggle();

const canNum = ref(0)

const dataForm = ref({
  app: "WA",
  bundle: void undefined, // app类型
  devices: void undefined, // 设备名称
  sim: void undefined, // 号码类型
  country: void undefined, // 国家名称
  mobile: void undefined, // 手机号
  status: void undefined, // 状态
  exported: void undefined, // 是否导出
  times: void undefined,
})
const rules = {}
const handleClose = () => {
  setDialogVisible(false)
}
const handleOpen = (params) => {
  resetForm()
  dataForm.value = JSON.parse(JSON.stringify(params))
  dataForm.value.exported = 'no'
  getCount()
  setDialogVisible(true)
}

const submitForm = async () => {
  setLoading(true)
  
  const params = formatParams(dataForm.value)
  params.devices && (params.devices = params.devices.split(","));
  const res = await exportAccount({ ...params, page: 1, size: canNum.value}, { responseType: 'blob' })

  const fileName = res.headers["content-disposition"] && res.headers["content-disposition"].split("=")[1];
  downloadZipFile(res.data, decodeURIComponent(fileName?.split("''")[1]) || 'default.tar')
  setLoading(false)
  setDialogVisible(false)
  return
}

const formRef = ref(null)
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}

const canNumCopy = ref(null)
const getCount = async () => {
  const params = JSON.parse(JSON.stringify(dataForm.value));
  params.devices && (params.devices = params.devices.split(","));

  const { count, rows } = await getAccountList({ page: 1, size: 10, ...params });
  canNum.value = count
  canNumCopy.value = count
};

defineExpose({
  handleOpen,
})
</script>
